const db = wx.cloud.database()
const App = getApp()
const _ = db.command
const MESSAGE = require('../../common/config/message.config.js')
const md5 = require('../../common/utils/md5.js')
const checkData = require('../../common/utils/check.js')
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: App.globalData.StatusBar,
    CustomBar: App.globalData.CustomBar,
    Custom: App.globalData.Custom,
    // 按钮禁用
    btnLoading: false,
    gender: ['男', '女', '保密'],
    // 性别选择数组下标
    GenderIdx: null,
    // 删除原来的图id
    removeFileID: "",
    // 个人信息对象
    userList: {

    },
    setUserInfo: {
      avatarUrl: "",
      nickName: "",
      email: "",
      gender: "",
      password: "",
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    // 获取用户信息
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息', UserInfo);
    // 获取身份标识
    this.setData({
      UserInfo: UserInfo,
      GenderIdx: UserInfo.gender
    })
    that.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 获取头像的临时路径
  onChooseAvatar(e) {
    that.setData({
      btnLoading: true
    })
    const {
      avatarUrl
    } = e.detail
    console.log("头像临时路径", avatarUrl);
    that.setData({
      'userList.avatarUrl': avatarUrl,
    })
    let cloudPath = "userPhoto/" + that.data.UserInfo.account + '时间' + Date.now() + ".png"
    wx.cloud.uploadFile({
      cloudPath: cloudPath, // 上传至云端的路径
      filePath: avatarUrl, // 小程序临时文件路径
      success: res => {
        // 返回文件 ID
        console.log(res.fileID)
        that.setData({
          ['setUserInfo.avatarUrl']: res.fileID,
          btnLoading: false
        })
        console.log('新头像', that.data.setUserInfo.avatarUrl);
      },
      fail: function (res) {
        that.setData({
          btnLoading: false
        })
      }
    })

  },
  // 获取input输入的值(名称、学号、邮箱)
  handleChange(e, key) {
    const {
      detail,
      currentTarget
    } = e
    console.log('currentTarget', currentTarget);
    let value = detail.value
    if (currentTarget.id === 'password') {
      value = md5.hexMD5(value)
    }
    console.log('value', value);
    this.setData({
      [`setUserInfo.${currentTarget.id}`]: value,
    })
  },


  // 性别
  ChangeGender: function (e) {
    console.log('性别picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      GenderIdx: e.detail.value,
      ['setUserInfo.gender']: e.detail.value,
    })
  },




  // 获取个人信息
  getUserInfo() {
    App.toast.showLoading('加载中')
    db.collection('userInfo').where({
        account: _.eq(that.data.UserInfo.account)
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          let userList = res.data[0]
          console.log('userList', userList)
          that.setData({
            userList: userList,
            'setUserInfo.avatarUrl': userList.avatarUrl,
            'setUserInfo.nickName': userList.nickName,
            'setUserInfo.email': userList.email,
            'setUserInfo.gender': userList.gender,
            GenderIdx: userList.gender,
            'setUserInfo.password': userList.password,
          })
        }
      })
  },
  // 效验
  check() {
    let that = this
    let setUserInfo = that.data.setUserInfo
    console.log('setUserInfo', setUserInfo);
    let email = checkData.checkEmail(setUserInfo.email, MESSAGE.ERROR_MESSAGE.CHECKEDEMAIL)
    if (!email) return
    that.setUser(setUserInfo)
  },

  // 提交更新后的用户信息
  setUser(e) {
    let setUserInfo = e
    console.log('即将更新的数据', setUserInfo);
    App.toast.showLoading('更新数据中')

    // 上传数据数据库
    db.collection('userInfo').where({
      _id: _.eq(that.data.UserInfo._id)
    }).update({
      data: {
        avatarUrl: setUserInfo.avatarUrl,
        nickName: setUserInfo.nickName,
        email: setUserInfo.email,
        gender: Number(setUserInfo.gender),
        password: setUserInfo.password
      },
      success: function (res) {
        db.collection('userInfo').where({
            account: _.eq(that.data.UserInfo.account)
          })
          .get({
            success: function (res) {
              App.toast.hideLoading()
              let userInfo = res.data[0]
              console.log('更新完毕，将用户信息储存起来', userInfo);
              delete userInfo.password
              delete userInfo._openid
              App.cache.setUserInfo(userInfo)
              console.log('更新成功', res);
              App.toast.showToast('更新成功，正在返回')
              that.navIndex()
            }
          })

      },
    })

  },
  // 跳转回首页
  navIndex() {
    // 通过判断当前页面的页面栈信息，是否有上一页进行返回
    const pages = getCurrentPages()
    if (pages.length == 1) {
      console.log('已经返回来了');
    } else {
      wx.navigateBack({
        delta: 1
      })
    }

  },
  // 退出登录
  Logout: function () {
    wx.showModal({
      title: '退出登录',
      content: '是否退出登录',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          App.cache.removeUserInfo()
          App.route.relTo('/pages/login/index')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  CancelTheAccount() {
    wx.showModal({
      title: '提示',
      content: '注销操作不可恢复！',
      success(res) {
        if (res.confirm) {
          App.toast.showLoading('删除中')
          db.collection('userInfo').doc(that.data.UserInfo._id).remove({
            success: function (res) {
              App.toast.hideLoading()
              wx.clearStorage({
                success: function (res) {
                  console.log('删除成功', res);
                  App.route.relTo('/pages/index/index')
                },
                fail: function (res) {
                  console.log('删除失败', res);
                }
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})